package com.dzh.controller;

import com.dzh.mapper.AgentMapper;
import com.dzh.mapper.CommentMapper;
import com.dzh.mapper.GalleyMapper;
import com.dzh.mapper.RecommendMapper;
import com.dzh.pojo.*;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.thymeleaf.util.DateUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletContext;


@MultipartConfig
@Controller
public class GalleyController {
    @Autowired
   private GalleyMapper galleyMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private RecommendMapper recommendMapper;
    @Autowired
    private AgentMapper agentMapper;
    @RequestMapping("/tolist")
    public String queryAllGalley(Model model,Integer pageNum){
//        PageHelper.startPage(1,5);
//        List<Galley> list = galleyMapper.queryAllGalley();
//        PageInfo<Galley> pageInfo = new PageInfo<>(list);
//        System.out.println(pageInfo);
//        model.addAttribute("GallyList",pageInfo.getList());

        //通过类型列出列表
        String a = "newest";
        String b = "popular";
        List<Recommend> recommends =  recommendMapper.queryGallyByType(a);
        List<Recommend> recommends1 =  recommendMapper.queryGallyByType(b);
        for(Recommend recommend:recommends){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }


        for(Recommend recommend:recommends1){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }

        model.addAttribute("newrecommendlist",recommends);


        if(pageNum==null){
            pageNum=1;
        }else{


             pageNum=pageNum.intValue();
        }
        PageHelper.startPage(pageNum,3);
        List<Galley> list = galleyMapper.queryAllGalley();
        PageInfo<Galley> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
        model.addAttribute("GallyList",pageInfo.getList());
        model.addAttribute("pages",pageInfo.getPages());
        return "property-list-view";
    }


    @RequestMapping("/todetail")
    public String todetail(Model model,Integer propertyid,HttpSession session){
     Galley galley =  galleyMapper.queryGalleyById(propertyid);
     session.setAttribute("propertyid",propertyid);
     //查询经理
        //查出来pid对应的aid是多少
        Integer aid = agentMapper.queryAidByPid(propertyid);
        //通过aid来查人
        Agent agent = agentMapper.queryAgentByAid(aid);
        model.addAttribute("agent",agent);

     //通过查找当前地产的评论然后将评论放进去
     List<Comment> comments = commentMapper.queryAllCommentById(propertyid);
     galley.setComments(comments);
     model.addAttribute("galleydetail",galley);



        //通过类型列出列表
        String a = "newest";
        String b = "popular";
        List<Recommend> recommends =  recommendMapper.queryGallyByType(a);
        List<Recommend> recommends1 =  recommendMapper.queryGallyByType(b);
        for(Recommend recommend:recommends){
            Galley galley1 =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley1);
        }


        for(Recommend recommend:recommends1){
            Galley galley2 =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley2);
        }

        model.addAttribute("newrecommendlist",recommends);




        return "property-detail";
    }


    @RequestMapping("/addcomment")
    public String addComment(Model model, HttpSession session, HttpServletRequest request){
        //丛前端获取参数，或者原本session里面自带的参数
      String username =(String)session.getAttribute("loginUser");
        Integer propertyid =Integer.parseInt(session.getAttribute("propertyid").toString());
     String name = request.getParameter("username");
     String email = request.getParameter("number");
     String message = request.getParameter("message");

     Comment comment = new Comment();
     comment.setEmail(email);
     comment.setUsername(name);
     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
     comment.setDate(df.format(new Date()));
     comment.setGid(propertyid);
     comment.setSay(message);
     commentMapper.addComments(comment);

     //查询当前的地产然后跳转页面显示出来
        //查询出当前地产的评论
        List<Comment> comments =  commentMapper.queryAllCommentById(propertyid);
  Galley galley = galleyMapper.queryGalleyById(propertyid);
  //将评论放进galley这个对象里，这样用一个model就可以了
  galley.setComments(comments);
     model.addAttribute("galleydetail",galley);


        Integer aid = agentMapper.queryAidByPid(propertyid);
        //通过aid来查人
        Agent agent = agentMapper.queryAgentByAid(aid);
        model.addAttribute("agent",agent);

        return "property-detail";
    }


    @RequestMapping("/midturn")
    public String midturn(){
      return "hello";
    }

    @RequestMapping("/searchindex")
    public String searchindex(HttpServletRequest request,HttpSession session,Model model){
          String type = request.getParameter("type");
          String title = request.getParameter("title");
          String address = request.getParameter("address");
          String bedrooms = request.getParameter("bedcount");
          String bathrooms = request.getParameter("bathcount");
//          String minprice = request.getParameter("minprice");
//          String maxprice = request.getParameter("maxprice");
        int minprice=Integer.parseInt(request.getParameter("minprice"));
        int maxprice=Integer.parseInt(request.getParameter("maxprice"));
      List<Galley> list =  galleyMapper.queryGallyBySearch(type,title,address,bedrooms,bathrooms,minprice,maxprice);
//      System.out.println(type);
//      System.out.println(title);
//      System.out.println(address);
//      System.out.println(bedrooms);
//      System.out.println(bathrooms);
//      System.out.println(minprice);
//      System.out.println(maxprice);
//
//
//      System.out.println(list);
        model.addAttribute("GallyList",list);




        //通过类型列出列表
        String a = "newest";
        String b = "popular";
        List<Recommend> recommends =  recommendMapper.queryGallyByType(a);
        List<Recommend> recommends1 =  recommendMapper.queryGallyByType(b);
        for(Recommend recommend:recommends){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }


        for(Recommend recommend:recommends1){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }

        model.addAttribute("newrecommendlist",recommends);







        return "property-list-view";
    }


    @RequestMapping("/searchlist")
    public String searchlist(HttpServletRequest request,HttpSession session,Model model){
       String type = request.getParameter("type");
       String city = request.getParameter("address");
       String status = request.getParameter("status");
       String bedrooms = request.getParameter("bedrooms");
       String bathrooms = request.getParameter("bathrooms");
       List<Galley> galleyList = galleyMapper.queryGallyBySearchlist(city,type,status,bedrooms,bathrooms);
       model.addAttribute("GallyList",galleyList);



        //通过类型列出列表
        String a = "newest";
        String b = "popular";
        List<Recommend> recommends =  recommendMapper.queryGallyByType(a);
        List<Recommend> recommends1 =  recommendMapper.queryGallyByType(b);
        for(Recommend recommend:recommends){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }


        for(Recommend recommend:recommends1){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }

        model.addAttribute("newrecommendlist",recommends);






       return "property-list-view";
    }

    @RequestMapping("/searchindexbysale")
    public String searchindexbysale(HttpServletRequest request,HttpSession session,Model model){
        String type = request.getParameter("type");
        String title = request.getParameter("title");
        String address = request.getParameter("address");
        String bedrooms =request.getParameter("bedcount");
        String bathrooms = request.getParameter("bathcount");
//          String minprice = request.getParameter("minprice");
//          String maxprice = request.getParameter("maxprice");
        int minprice=Integer.parseInt(request.getParameter("minprice"));
        int maxprice=Integer.parseInt(request.getParameter("maxprice"));
        List<Galley> list =  galleyMapper.queryGallyBySearchBysale(type,title,address,bedrooms,bathrooms,minprice,maxprice);
//      System.out.println(type);
//      System.out.println(title);
//      System.out.println(address);
//      System.out.println(bedrooms);
//      System.out.println(bathrooms);
//      System.out.println(minprice);
//      System.out.println(maxprice);
//
//
//      System.out.println(list);



        //通过类型列出列表
        String a = "newest";
        String b = "popular";
        List<Recommend> recommends =  recommendMapper.queryGallyByType(a);
        List<Recommend> recommends1 =  recommendMapper.queryGallyByType(b);
        for(Recommend recommend:recommends){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }


        for(Recommend recommend:recommends1){
            Galley galley =  galleyMapper.queryGalleyById(recommend.getGid());
            recommend.setGalleys(galley);
        }

        model.addAttribute("newrecommendlist",recommends);






        model.addAttribute("GallyList",list);
        return "property-list-view";
    }


//    @RequestMapping("/upload")
//    public String upload(Model model, HttpServletRequest request, HttpServlet servlet, MultipartFile img1)  throws IOException {
//        String name = request.getParameter("name");
//        String location = request.getParameter("location");
//        double price = Integer.parseInt(request.getParameter("price"));
//        double size = Integer.parseInt(request.getParameter("size"));
//        String address = request.getParameter("address");
//        String city = request.getParameter("city");
//        int bedrooms = Integer.parseInt(request.getParameter("bedrooms"));
//        int bathrooms = Integer.parseInt(request.getParameter("bathrooms"));
//        String detail = request.getParameter("detail");
//        String detail2 = request.getParameter("detail2");
//        String type = request.getParameter("type");
//        String status = request.getParameter("status");
//
//
//
//        return "submit";
//
//    }





    @PostMapping("/upload")
    public String fileUpload(@RequestParam("img1")MultipartFile srcFile,  @RequestParam("img2")MultipartFile srcFile2,RedirectAttributes redirectAttributes,HttpServletRequest request,Model model) {



//        String name = request.getParameter("name");
//        String location = request.getParameter("location");
//        int price = Integer.parseInt(request.getParameter("price"));
//        int size = Integer.parseInt(request.getParameter("size"));
//        String address = request.getParameter("address");
//        String city = request.getParameter("city");
//        int bedrooms = Integer.parseInt(request.getParameter("bedrooms"));
//        int bathrooms = Integer.parseInt(request.getParameter("bathrooms"));
//        String detail = request.getParameter("detail");
//        String detail2 = request.getParameter("detail2");
//        String type = request.getParameter("type");
//        String status = request.getParameter("status");





//前端没有选择文件，srcFile为空
//选择了文件，开始上传操作
        try {
//构建上传目标路径，找到了项目的target的classes目录
            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!destFile.exists()) {
                destFile = new File("");
            }
//输出目标文件的绝对路径
            System.out.println("file path:"+destFile.getAbsolutePath());
//拼接子路径
            SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
            String times = sf_.format(new Date());
            File upload = new File(destFile.getAbsolutePath(), "static/images/resource");
//若目标文件夹不存在，则创建
            if(!upload.exists()) {
                upload.mkdirs();
            }
            System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile);
            System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile2);
//根据srcFile大小，准备一个字节数组
            byte[] bytes = srcFile.getBytes();
            byte[] bytes2 = srcFile2.getBytes();
//拼接上传路径
//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
//通过项目路径，拼接上传路径
            Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
            Path path2 = Paths.get(upload.getAbsolutePath()+"/"+srcFile2.getOriginalFilename());
//** 开始将源文件写入目标地址
            Files.write(path, bytes);
            Files.write(path2, bytes2);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
            String fileName = srcFile.getOriginalFilename();
            String fileName2 = srcFile2.getOriginalFilename();
// 获得文件后缀名称
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            String suffixName2 = fileName2.substring(fileName2.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名称
//            String newFileName = uuid + "."+ suffixName;
//            redirectAttributes.addFlashAttribute("message", "文件上传成功"+newFileName);
            System.out.println(fileName);
            System.out.println(path);
            String aaa ="images/resource/";
            String bbb1 = aaa+fileName;
            String bbb2 = aaa+fileName2;
            System.out.println(bbb1);
            System.out.println(bbb2);





            String name = request.getParameter("name");
            String location = request.getParameter("location");
            int price = Integer.parseInt(request.getParameter("price"));
            int size = Integer.parseInt(request.getParameter("size"));
            String address = request.getParameter("address");
            String city = request.getParameter("city");
            int bedrooms = Integer.parseInt(request.getParameter("bedrooms"));
            int bathrooms = Integer.parseInt(request.getParameter("bathrooms"));
            String detail = request.getParameter("detail");
            String detail2 = request.getParameter("detail2");
            String type = request.getParameter("type");
            String status = request.getParameter("status");
            String aname = request.getParameter("aname");
            String img1 = bbb1;
            String img2 = bbb2;


            Galley galley = new Galley();
            galley.setName(name);
            galley.setLocation(location);
            galley.setPrice(price);
            galley.setSize(size);
            galley.setAddress(address);
            galley.setCity(city);
            galley.setBedrooms(bedrooms);
            galley.setBathrooms(bathrooms);
            galley.setDetail(detail);
            galley.setDetail2(detail2);
            galley.setType(type);
            galley.setStatus(status);
            galley.setImg(bbb1);
            galley.setImg2(bbb2);
            galleyMapper.insertGally(galley);

           Integer pid =  galleyMapper.queryPidByImg(bbb1);
           Integer aid = agentMapper.queryAidByName(aname);
            AgentProperties agentProperties = new AgentProperties();
            agentProperties.setAid(aid);
            agentProperties.setPid(pid);
            agentMapper.insertAP(agentProperties);

            //通过类型列出列表
            String a = "newest";
            String b = "popular";
            List<Recommend> recommends =  recommendMapper.queryGallyByType(a);
            List<Recommend> recommends1 =  recommendMapper.queryGallyByType(b);
            for(Recommend recommend:recommends){
                Galley galley1 =  galleyMapper.queryGalleyById(recommend.getGid());
                recommend.setGalleys(galley1);
            }


            for(Recommend recommend:recommends1){
                Galley galley2 =  galleyMapper.queryGalleyById(recommend.getGid());
                recommend.setGalleys(galley2);
            }

            model.addAttribute("newrecommendlist",recommends);



//            List<Galley> list = galleyMapper.queryAllGalley();
//            model.addAttribute("GallyList",list);



        } catch (IOException e) {
            e.printStackTrace();
        }






        return "property-list-view";




    }






}
